package xyz.xxdl.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class BtmxUtils {
    private static String ROUTE_PREFIX = "api/pro/v1";
    // 将私钥封装加密
    public static String sign(String message, String secret) {
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secretKeySpec);
            return new String(Base64.getEncoder().encode(sha256_HMAC.doFinal(message.getBytes())));
        } catch (Exception e) {
            throw new RuntimeException("Unable to sign message.", e);
        }
    }

    /*
     * @url 请求地址
     * @heads 需要的请求头,类似键值对
     * @params 需要的参数,类型键值对
     *
     * */
    public static JSONObject doGet(String url, Map<String, String> heads, Map<String, String> params) {
        String later = "";
        // 提升变量
        String result = "";
        BufferedReader in = null;
        if (params != null) {
            for (String s1 : params.keySet()) {
                later = later + s1 + "=" + params.get(s1) + "&";
            }
        }
        url = url + "?" + later;
        try {
            URL trueUrl = new URL(url);
            URLConnection connection = trueUrl.openConnection();
            if (heads != null) {
                // 设置通用的请求属性
                for (String s : heads.keySet()) {
                    connection.setRequestProperty(s, heads.get(s));
                }
            }
            System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
            // 建立实际的连接
            connection.connect();
            // 获取连接的输入流
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送请求出错" + e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return JSON.parseObject(result);
    }

    public static JSONObject sendHttpRequest(String url, Map<String, String> heads) {
        // 提升变量
        String result = "";
        BufferedReader in = null;
        try {
            URL trueUrl = new URL(url);
            URLConnection connection = trueUrl.openConnection();
            if (heads!=null){
                // 设置通用的请求属性
                for (String s : heads.keySet()) {
                    connection.setRequestProperty(s, heads.get(s));
                }
            }
            // 建立实际的连接
            connection.connect();
            // 获取连接的输入流
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println(url);
        } catch (Exception e) {
            System.out.println("发送请求出错" + e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return JSON.parseObject(result);
    }



    public static JSONObject doPost(String RequestMethod, String url, Map<String, String> heads, Map<String, Object> params) {
        String param = "";
        // 变量提升
        String result = "";
        BufferedReader in = null;
        PrintWriter printWriter = null;
        try {
            if (params != null) {
                ObjectMapper mapper = new ObjectMapper();
                param = mapper.writeValueAsString(params);
            }

            URL trueUrl = new URL(url);
            URLConnection connection = trueUrl.openConnection();
            HttpURLConnection conn = (HttpURLConnection) connection;
//            System.out.println("hea参数是");
            if (heads != null) {
                // 设置通用的请求属性
                for (String s : heads.keySet()) {
                    conn.setRequestProperty(s, heads.get(s));
//                    System.out.println(heads.get(s));
                }
            }
            conn.setRequestMethod(RequestMethod);
            conn.setRequestProperty("Content-Type","application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            printWriter = new PrintWriter(conn.getOutputStream());
//            System.out.println("url是\n" + url);
//            System.out.println("post参数是\n"+param);
            printWriter.write(param);
            printWriter.flush();
            // 获取连接的输入流
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送请求出错" + e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (printWriter != null) {
                try {
                    printWriter.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = null;
        return JSON.parseObject(result);
    }


    public static Map<String, String> make_auth_headers(Long timestamp, String path, String apikey, String secret) {
        HashMap<String, String> hashMap = new HashMap<>();
        try {
            String Strtimestamp = timestamp.toString();
            String msg = timestamp.toString() + "+" + path;

            hashMap.put("x-auth-key", apikey);
            hashMap.put("x-auth-signature", sign(msg, secret));
            hashMap.put("x-auth-timestamp", Strtimestamp);

        } catch (Exception e) {
            System.out.println("请求头拼接错误");
            e.printStackTrace();
        }
        if (hashMap.size() != 0) {
            return hashMap;
        } else {
            System.out.println("请求头为空");
            return null;
        }
    }

    // 获取时间戳
    public static Long utc_timestamp() {
        return System.currentTimeMillis();
    }
}
